package com.example.dictionary.service;

import com.example.memento.model.WordModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 多委托实现代理类
 * 支持同时使用多个 DictionaryDelegate 实现
 * 默认使用 RocksDB，可同时使用 SQLite 等
 */
@Service("multiDictionaryDelegate")
public class MultiDictionaryDelegate implements DictionaryDelegate {
    
    private static final Logger log = LoggerFactory.getLogger(MultiDictionaryDelegate.class);
    
    // 主委托（默认使用 RocksDB）
    private final DictionaryDelegate primaryDelegate;
    
    // 辅助委托列表（可选）
    private final List<DictionaryDelegate> secondaryDelegates;
    
    /**
     * 构造函数
     * 默认使用 RocksDB 作为主委托
     */
    @Autowired
    public MultiDictionaryDelegate(
            @Qualifier("rocksDBDictionaryDelegate") DictionaryDelegate primaryDelegate,
            @Autowired(required = false) List<DictionaryDelegate> allDelegates) {
        this.primaryDelegate = primaryDelegate;
        
        // 收集除主委托外的所有委托
        this.secondaryDelegates = new ArrayList<>();
        if (allDelegates != null) {
            for (DictionaryDelegate delegate : allDelegates) {
                // 排除主委托、自己和 MultiDictionaryDelegate 的实例
                if (delegate != primaryDelegate && !(delegate instanceof MultiDictionaryDelegate)) {
                    this.secondaryDelegates.add(delegate);
                    log.info("添加辅助委托: {}", delegate.getClass().getSimpleName());
                }
            }
        }
        
        log.info("MultiDictionaryDelegate 初始化完成 - 主委托: {}, 辅助委托数量: {}", 
                primaryDelegate.getClass().getSimpleName(), secondaryDelegates.size());
    }
    
    @Override
    public Optional<WordModel> findWord(String wordName) {
        // 先从主委托查询
        Optional<WordModel> result = primaryDelegate.findWord(wordName);
        
        if (result.isPresent()) {
            return result;
        }
        
        // 如果主委托没有找到，从辅助委托查询
        for (DictionaryDelegate delegate : secondaryDelegates) {
            try {
                result = delegate.findWord(wordName);
                if (result.isPresent()) {
                    log.debug("从辅助委托 {} 找到词汇: {}", 
                            delegate.getClass().getSimpleName(), wordName);
                    // 可选：将找到的词汇同步到主委托
                    // primaryDelegate.saveWord(result.get());
                    return result;
                }
            } catch (Exception e) {
                log.warn("从辅助委托 {} 查询词汇失败: {}", 
                        delegate.getClass().getSimpleName(), wordName, e);
            }
        }
        
        return Optional.empty();
    }
    
    @Override
    public WordModel saveWord(WordModel wordModel) {
        // 先保存到主委托
        WordModel saved = primaryDelegate.saveWord(wordModel);
        
        // 同时保存到所有辅助委托（异步或同步）
        for (DictionaryDelegate delegate : secondaryDelegates) {
            try {
                delegate.saveWord(wordModel);
                log.debug("同步保存到辅助委托: {}", delegate.getClass().getSimpleName());
            } catch (Exception e) {
                log.warn("保存到辅助委托 {} 失败", delegate.getClass().getSimpleName(), e);
                // 继续保存到其他委托，不中断
            }
        }
        
        return saved;
    }
    
    @Override
    public boolean existsWord(String wordName) {
        // 先检查主委托
        if (primaryDelegate.existsWord(wordName)) {
            return true;
        }
        
        // 检查辅助委托
        for (DictionaryDelegate delegate : secondaryDelegates) {
            try {
                if (delegate.existsWord(wordName)) {
                    return true;
                }
            } catch (Exception e) {
                log.warn("检查辅助委托 {} 是否存在词汇失败", 
                        delegate.getClass().getSimpleName(), e);
            }
        }
        
        return false;
    }
    
    /**
     * 获取主委托
     */
    public DictionaryDelegate getPrimaryDelegate() {
        return primaryDelegate;
    }
    
    /**
     * 获取所有辅助委托
     */
    public List<DictionaryDelegate> getSecondaryDelegates() {
        return new ArrayList<>(secondaryDelegates);
    }
}

